// fileService.ts
import { saveAsset, saveRelation, createDevice } from '/@/api/thingsborad/entity/entity';
import type {
  saveAssetParams,
  saveRelationParams,
  addBasicDeviceParams,
} from '/@/api/thingsborad/entity/model/entityModel';
import { computed } from 'vue';
import { addTimestamp } from '/@/views/DigitalTwin/newleft/service/timestamp';
import { FileLoadUrl } from '/@/core/communication/interface/ISendUnity';
import {
  getAssetProfileId,
  getDeviceProfilesId,
} from '/@/views/DigitalTwin/newleft/service/defaultId';
import store from '../manage/store';
// 文件上传函数
export const uploadToServer = (
  file: File,
  onProgress: (percent: number) => void,
): Promise<string> => {
  const formData = new FormData();
  formData.append('file', file);

  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        const percentCompleted = Math.round((event.loaded * 100) / event.total);
        onProgress(percentCompleted);
      }
    };

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        resolve(JSON.parse(xhr.responseText).filename);
      } else {
        reject(new Error('文件上传失败'));
      }
    };

    xhr.onerror = () => reject(new Error('网络错误'));
    xhr.open('POST', `${FileLoadUrl}api/upload`, true);
    xhr.send(formData);
  });
};

// 保存数据
export const saveUploadData = async (
  filename: string,
  url: string,
  itemId: string,
): Promise<void> => {
  const newFilename = addTimestamp(filename);
  const assetId = await getAssetProfileId();
  const assetParams: saveAssetParams = {
    name: newFilename,
    assetProfileId: {
      entityType: 'ASSET_PROFILE',
      id: assetId,
    },
    customerId: null,
    additionalInfo: { description: url },
  };

  try {
    const asset = await saveAsset(assetParams);
    const relationParams: saveRelationParams = {
      type: 'Contains',
      additionalInfo: {},
      typeGroup: 'COMMON',
      from: { entityType: 'ASSET', id: itemId },
      to: asset.id,
    };
    await saveRelation(relationParams);
  } catch (error) {
    throw new Error(`操作失败：${error}`);
  }
};

// 设备保存
export const saveDevicePlan = async (filename: string, url: string): Promise<void> => {
  // 处理文件名，替换旧时间戳为新时间戳
  const processFilename = (originalName: string): string => {
    const splitIndex = originalName.indexOf('-');
    const newTimestamp = Date.now().toString();
    if (splitIndex === -1) {
      // 如果没有连字符，直接添加新时间戳
      return `${newTimestamp}-${originalName}`;
    } else {
      // 截取连字符后的部分作为描述和扩展名
      const descriptionPart = originalName.substring(splitIndex + 1);
      return `${newTimestamp}-${descriptionPart}`;
    }
  };

  const deviceId = await getDeviceProfilesId();
  const deviceFilename = processFilename(filename);
  const deviceParams: addBasicDeviceParams = {
    name: deviceFilename,
    deviceProfileId: {
      entityType: 'DEVICE_PROFILE',
      id: deviceId, // 保持固定值
    },
    customerId: null,
    additionalInfo: {
      gateway: false,
      overwriteActivityTime: false,
      description: url, // 使用传入的URL
    },
  };

  try {
    const device = await createDevice(deviceParams);
    const selectedItemId = computed(() => store.state.selectedIssue?.to.id);
    const relationParams: saveRelationParams = {
      type: 'Contains',
      additionalInfo: {},
      typeGroup: 'COMMON',
      from: {
        entityType: 'ASSET',
        id: selectedItemId.value, // 父级资产ID
      },
      to: device.id,
    };
    await saveRelation(relationParams);
  } catch (error) {
    throw new Error(`设备方案保存失败：${error instanceof Error ? error.message : error}`);
  }
};

// 创建方案
export const createPlan = async (
  itemId: string,
  newFolderName: string,
  activeSecond: string,
  setErrorMessage: (msg: string) => void,
  setDialogVisible: (visible: boolean) => void,
): Promise<{
  data: {
    to: { id: any; entityType: string };
    toName: string;
    from: { id: string; entityType: string };
    type: string;
    typeGroup: string;
    additionalInfo: string;
  };
}> => {
  if (!newFolderName.trim()) {
    setErrorMessage('方案名称不能为空');
  }

  try {
    const assetId = await getAssetProfileId();
    // 创建资产参数
    const assetParams: saveAssetParams = {
      name: `${activeSecond}-${newFolderName.trim()}`,
      assetProfileId: {
        entityType: 'ASSET_PROFILE',
        id: assetId,
      },
      additionalInfo: {
        description: newFolderName,
      },
      customerId: null,
    };

    // 保存资产
    const asset = await saveAsset(assetParams);

    // 创建关联关系
    const relationParams: saveRelationParams = {
      type: 'Contains',
      additionalInfo: {},
      typeGroup: 'COMMON',
      from: {
        entityType: 'ASSET',
        id: itemId,
      },
      to: asset.id,
    };

    await saveRelation(relationParams);
    setDialogVisible(false);
    return {
      data: {
        to: {
          id: asset.id,
          entityType: 'ASSET',
        },
        toName: `${activeSecond}-${newFolderName.trim()}`, // 保持命名规则
        from: {
          id: itemId,
          entityType: 'ASSET',
        },
        type: 'Contains',
        typeGroup: 'COMMON',
        additionalInfo: '',
      },
    };
  } catch (error) {
    setErrorMessage(`创建失败: ${(error as Error).message}`);
    throw error;
  }
};

// 创建文件夹
export const createFolder = async (
  newFolderName: string,
  activeSecond: string,
  setErrorMessage: (msg: string) => void,
  setDialogVisible: (visible: boolean) => void,
  refreshData: () => Promise<void>,
) => {
  if (!newFolderName.trim()) {
    setErrorMessage('文件夹名称不能为空');
    return;
  }

  const parentId = activeSecond;
  if (!parentId) {
    setErrorMessage('请选择第二层目录');
    return;
  }

  try {
    const assetId = await getAssetProfileId();
    // 创建资产参数
    const assetParams: saveAssetParams = {
      name: `${parentId}-${newFolderName.trim()}`,
      assetProfileId: {
        entityType: 'ASSET_PROFILE',
        id: assetId,
      },
      additionalInfo: {
        description: newFolderName,
      },
      customerId: null,
    };

    // 保存资产
    const asset = await saveAsset(assetParams);

    // 创建关联关系
    const relationParams: saveRelationParams = {
      type: 'Contains',
      additionalInfo: {},
      typeGroup: 'COMMON',
      from: {
        entityType: 'ASSET',
        id: parentId,
      },
      to: asset.id,
    };

    await saveRelation(relationParams);
    await refreshData();
    setDialogVisible(false);
    return true;
  } catch (error) {
    setErrorMessage(`创建失败: ${(error as Error).message}`);
    throw error;
  }
};
//下载
type ProgressCallback = (progress: number) => void;
export const FileService = {
  async uploadFile(file: File, onProgress?: ProgressCallback): Promise<string> {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();

      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable && onProgress) {
          const percent = Math.round((event.loaded * 100) / event.total);
          onProgress(percent);
        }
      };

      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          try {
            const response = JSON.parse(xhr.responseText);
            resolve(response.filename);
          } catch (e) {
            reject(new Error('无效的响应格式'));
          }
        } else {
          reject(new Error(`上传失败: ${xhr.statusText}`));
        }
      };

      xhr.onerror = () => reject(new Error('网络错误'));
      xhr.open('POST', `${FileLoadUrl}api/upload`, true);
      xhr.send(formData);
    });
  },

  getDownloadUrl(filename: string): string {
    return `http://localhost:8089/download/${encodeURIComponent(filename)}`;
  },

  triggerDownload(filename: string) {
    const url = this.getDownloadUrl(filename);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  },
};

// export interface saveRelationParams {
//   type: string;
//   additionalInfo: object;
//   typeGroup: string;
//   from: {
//     entityType: string;
//     id: string;
//   };
//   to: string;
// }
